#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "student.h"
#include "admin.h"

// 打印登录菜单函数
void printf_login_menu()
{
    printf("         欢迎来到学生管理系统           \n");
    printf("----------------------------------------\n");
    printf("| 1、登录\t\t\t       |\n");
    printf("| 2、注册\t\t\t       |\n");
    printf("| 0、退出\t\t\t       |\n");
    printf("----------------------------------------\n");
    printf("请输入相应的序号选择!          \n");
}

// 执行登录菜单
int menuOperate_login(int menu, int login_flag, Admin_p admin, int *admin_index)
{
    system("cls"); // 清空控制台内容
    switch (menu)
    {
    case LOGIN:
        return login(login_flag, admin, admin_index);
        break;
    case ENROLL:
        enroll(admin, admin_index);
        break;
    case EXIT_SYSTEM:
        printf("退出成功!");
        exit(0);
    default:
        break;
    }
    return 0;
}

// 登录
int login(int login_flag, Admin_p admin, int *admin_index)
{
    printf("                  登录                  \n");
    printf("----------------------------------------\n");
    char username[100];
    char password[100];
    printf("请输入账号:");
    scanf("%99s", username);
    printf("请输入密码:");
    scanf("%99s", password);
    if (verify_username(admin, admin_index, username) == -1)
    {
        printf("用户名不存在!\n");
        return 0;
    }
    else
    {
        if (strcmp(admin[verify_username(admin, admin_index, username)].password, password) == 0)
        {
            printf("登录成功!\n");
            return 1;
        }
        else
        {
            printf("密码错误!\n");
            return 0;
        }
    }
}

// 验证用户名是否存在
int verify_username(Admin_p admin, int *admin_index, char *username)
{
    for (int index = 0; index < *admin_index; index++)
    {
        if (!strcmp(admin[index].username, username))
        {
            return index; // 返回用户名对应的索引
        }
    }
    return -1; // 返回-1表示用户名不存在
}

// 验证密码是否正确
int verify_password(Admin_p admin, int *admin_index, char *username, char *password)
{
    for (int index = 0; index < *admin_index; index++)
    {
        if (!strcmp(admin[index].username, username))
        {
            if (!strcmp(admin[index].password, password))
            {
                return 1;
            }
            else
            {
                printf("密码错误!\n");
                return -1;
            }
        }
    }
}

// 注册
void enroll(Admin_p admin, int *admin_index)
{
    printf("                  注册                  \n");
    printf("----------------------------------------\n");
    char username[10];
    char password[10];
    printf("请输入用户名:");
    scanf("%s", username);
    if (verify_username(admin, admin_index, username) == -1)
    {
        printf("请输入密码:");
        scanf("%s", password);
        printf("注册成功!\n");
        strcpy(admin[*admin_index].username, username);
        strcpy(admin[*admin_index].password, password);
        (*admin_index)++;
    }
    else
    {
        printf("用户名已存在!\n");
        return;
    }
}
